package com.kl.alipay;



import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;


import com.kl.alipay.po.*;
import com.kl.config.AlipayConfig;


import com.kl.domain.CouponDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.SeckillCoupon;
import com.kl.entity.SeckillOrder;
import com.kl.entity.UserCoupon;
import com.kl.service.ISeckillOrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("alipayCallback")
public class AlipayCallback {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ISeckillOrderService iSeckillOrderService;

    //同步回调
    @RequestMapping("returnUrl")
    @ResponseBody
    public String returnUrl(HttpServletRequest request, String out_trade_no, String trade_no, String total_amount, Model model) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = getfind(request);
        //验证数字签名(验签)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        //如果成功 说明没有被篡改 如果失败 1.被篡改 2.编码有问题或者数据丢失
        System.out.println("进入同步回调方法");
        if(signVerified) {
            //商户订单号
            //支付宝交易号
            //付款金额
            //out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
            System.out.println("进入同步回调方法验签成功>>>>>>>>");
            model.addAttribute("out_trade_no",out_trade_no);
            model.addAttribute("trade_no",trade_no);
            model.addAttribute("total_amount",total_amount);

            return "paysuccess";
        }else {
            System.out.println("进入同步回调方法验签失败>>>>>>>>");
            return "payfail";
        }
        //——请在这里编写您的程序（以上代码仅作参考）——

    }
    //异步回调
    //商户订单号out_trade_no
    //支付宝交易号trade_no
    //交易状态trade_status
    @RequestMapping("notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request, String out_trade_no, String trade_no,String trade_status) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = getfind(request);

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        Map<String,String[]> requestParams = request.getParameterMap();
        System.out.println("进入异步回调方法>>>>>>>>");
        if(signVerified) {//验证成功
            System.out.println("进入异步回调方法验签成功>>>>>>>>");
            //关闭交易
            if(trade_status.equals("TRADE_FINISHED")){

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //支付成功和退款成功都会到这个方法
                System.out.println("进入异步回调方法支付成功>>>>>>>>");

                //判断该笔订单是否在商户网站中已经做过处理(解决幂等性问题,因为支付宝会多次重试,如以做处理,就无需处理);
               //借助于redis

                String[] gmt_refunds = requestParams.get("gmt_refund");
                if (gmt_refunds != null){ //说明是退款进来的
                    if (!redisTemplate.boundHashOps("alipay").hasKey(out_trade_no + "gmt_refunds")){
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //修改订单状态为已支付
                        //调用dubbo接口修改订单状态

                    }

                }else {
                    if (!redisTemplate.boundHashOps("alipay").hasKey(out_trade_no + "trade")){
                        System.out.println("进入方法");
                        //修改订单状态 和添加流水号
                        //调用RocketMQ执行分布式事务 分别执行订单状态修改 和增加积分 柔性事务,保证事务的最终一致性

                        //修改状态
                        //商户订单号out_trade_no
                        //支付宝交易号trade_no
                        SeckillOrder seckillOrder = new SeckillOrder();
                        seckillOrder.setPaymentStatus(2);
                        seckillOrder.setId(Long.parseLong(out_trade_no));
                        seckillOrder.setSerialNumber(trade_no);
                        seckillOrder.setTimePayment(new Date());
                        seckillOrder.setOrderUpdatetime(new Date());
                        seckillOrder.setOrderUpdatetime(new Date());
                        seckillOrder.setDeliveryTime(new Date());
                        seckillOrder.setTransactionCompletiontime(new Date());
                        seckillOrder.updateById();


                        //中间表(秒杀订单表 -> 中间表)回查
                        SeckillOrder seckillOrder2 = new SeckillOrder();
                        seckillOrder2.setId(Long.parseLong(out_trade_no));
                        SeckillOrder seckillOrder1 = seckillOrder2.selectById();
                        //秒杀优惠卷表 回查

                        SeckillCoupon seckillCoupon1 =(SeckillCoupon)redisTemplate.boundHashOps("kl_SeckillCoupon").get(seckillOrder1.getSeckillCouponId());

                    /*    SeckillCoupon seckillCoupon = new SeckillCoupon();
                        seckillCoupon.setSeckillCouponId(seckillOrder1.getSeckillCouponId());
                        SeckillCoupon seckillCoupon1 = seckillCoupon.selectById();*/


                        UserCoupon userCoupon = new UserCoupon();
                        userCoupon.setCouponId(seckillOrder1.getSeckillCouponId());
                        userCoupon.setUserId(seckillOrder1.getUserId());
                        userCoupon.insert();

                        //调用接口 添加优惠卷表 (秒杀订单表,秒杀优惠卷表 -> 中间表)
                        CouponDTO couponDTO = new CouponDTO();
                        couponDTO.setCouponType("3");
                        couponDTO.setStartTime(seckillCoupon1.getStatrTime());
                        couponDTO.setEndTime(seckillCoupon1.getEndTime());
                        couponDTO.setCrateTime(new Date());
                        couponDTO.setCouponSum(seckillCoupon1.getCouponSum());
                        couponDTO.setCouponSerial(seckillCoupon1.getCouponSerial());
                        couponDTO.setCouponCondition(seckillCoupon1.getCouponCondition());




                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //修改订单状态为已支付

                    }
                }


                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            return "success";

        }else {//验证失败
            //out.println("fail");
            return "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
        //——请在这里编写您的程序（以上代码仅作参考）——
    }


    /* 交易查询
     * 商户订单号，商户网站订单系统中唯一订单号 WIDTQout_trade_no
       支付宝交易号(流水号) WIDTQtrade_no
     */
    @RequestMapping("alipayTradeQuery")
    @ResponseBody
    public Result alipayTradeQuery(String WIDTQout_trade_no, String WIDTQtrade_no) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //商户订单号,支付宝交易号请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTQout_trade_no +"\","+"\"trade_no\":\""+ WIDTQtrade_no +"\"}");
        //请求
         String results = alipayClient.execute(alipayRequest).getBody();

         AlipayBaseResult alipayBaseResult = JSONObject.parseObject(results,AlipayBaseResult.class);

         AlipayResponsePo response = alipayBaseResult.getAlipay_trade_query_response();

         if (response == null){
            return Result.build(ConstantEnum.ERROR).setResult("支付宝查询失败,没有这条数据");
         }

         if (response.getCode() != null && response.getCode().intValue() == 10000){
            return Result.build(ConstantEnum.SUCCESS).setResult(response);
         }
        //输出
        return Result.build(ConstantEnum.ERROR);
    }
    /*退款
     *
     */
    //商户订单号，商户网站订单系统中唯一订单号 WIDTRout_trade_no
    //支付宝交易号 WIDTRtrade_no
    //请二选一设置
    //需要退款的金额，该金额不能大于订单金额，必填 WIDTRrefund_amount
    //退款的原因说明 WIDTRrefund_reason
    //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传 WIDTRout_request_no
    @RequestMapping("alipayTradeRefund")
    @ResponseBody
    public Result alipayTradeRefund(String WIDTRout_trade_no,String WIDTRtrade_no,String WIDTRrefund_amount,String WIDTRrefund_reason,String WIDTRout_request_no) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTRout_trade_no +"\","
                + "\"trade_no\":\""+ WIDTRtrade_no +"\","
                + "\"refund_amount\":\""+ WIDTRrefund_amount +"\","
                + "\"refund_reason\":\""+ WIDTRrefund_reason +"\","
                + "\"out_request_no\":\""+ WIDTRout_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        AiPayBaseRefund refund = JSONObject.parseObject(result, AiPayBaseRefund.class);
        AliPayRefundPo refundResponse = refund.getAlipay_trade_refund_response();

        if (refundResponse == null){
            return Result.build(ConstantEnum.ERROR).setResult("支付宝退款失败");
        }

        if (refundResponse.getCode() != null && refundResponse.getCode().intValue() == 10000){
            return Result.build(ConstantEnum.SUCCESS).setResult(refund);
            //修改订单状态

        }
        //输出
        return Result.build(ConstantEnum.ERROR);



    }

    //退款查询

    //商户订单号，商户网站订单系统中唯一订单号 WIDRQout_trade_no
    //支付宝交易号 WIDRQtrade_no
    //请二选一设置
    //请求退款接口时，传入的退款请求号，如果在退款请求时未传入，则该值为创建交易时的外部交易号，必填 WIDRQout_request_no
    @RequestMapping("alipayTradeFastpayRefundQuery")
    @ResponseBody
    public Result alipayTradeFastpayRefundQuery(String WIDRQout_trade_no,String WIDRQtrade_no,String WIDRQout_request_no) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDRQout_trade_no +"\","
                +"\"trade_no\":\""+ WIDRQtrade_no +"\","
                +"\"out_request_no\":\""+ WIDRQout_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        AliPayBaseRefundQuery refundQuery = JSONObject.parseObject(result, AliPayBaseRefundQuery.class);

        AlPayRefundQuery responseQuery = refundQuery.getAlipay_trade_fastpay_refund_query_response();


        if (responseQuery == null){
            return Result.build(ConstantEnum.ERROR).setResult("支付宝退款查询失败");
        }

        if (responseQuery.getCode() != null && responseQuery.getCode().intValue() == 10000){
            return Result.build(ConstantEnum.SUCCESS).setResult(refundQuery);
        }
        //输出
        return Result.build(ConstantEnum.ERROR);
    }




    //封装方法
    private Map<String,String> getfind(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
           // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }
}
